package com.yonyou.wdt.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.yonyou.wdt.entity.QueryDto;
import com.yonyou.wdt.service.YonsuiteService;
import com.yonyou.wdt.utils.WdtClient;
import com.yonyou.wdt.utils.WdtConfigProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author YJY
 * @data 2024/5/29
 * @User PC
 * @Msg
 */
@Service
public class SyncProductInsertImpl implements SyncProductInsert {

    private final WdtConfigProperties configProperties;

    @Resource
    private YonsuiteService yonsuiteService;

    @Autowired
    public SyncProductInsertImpl(WdtConfigProperties configProperties) {
        this.configProperties = configProperties;
    }

    private static final Logger logger = LoggerFactory.getLogger(SyncProductInsert.class);

    /**
     * @Author Yjy
     * @Description 检查事件推送回调地址
     * @Date 16:28 2023/10/11
     **/
    @Async
    @Override
    public void checkAsync() {

    }

    /**
     * @Author Yjy
     * @Description 物料档案新增事件
     * @Date 16:28 2023/10/11
     **/
    @Async
    @Override
    public void productInsert(String contentData) {
        // 解析YS数据
        JSONObject contentJSON = JSONUtil.parseObj(contentData);
        JSONObject productJSON = contentJSON.getJSONObject("archive");

        String manageClassCode = productJSON.getStr("manageClass_Code");

       // if (manageClassCode.contains("CP") || manageClassCode.contains("YW") || manageClassCode.contains("FY") || manageClassCode.contains("YG")) {

            // TODO Auto-generated method stub
            WdtClient client = new WdtClient(configProperties.getSid(), configProperties.getKey(), configProperties.getSecret(), configProperties.getUrl());
            //测试环境sid、appkey、密钥请到旺店通开放平台-自助对接-申请测试环境内查看，测试环境url=https://sandbox.wangdian.cn/openapi2/
            //调用正式环境时请将sid、appkey、appsecret切换为实际参数，参数在旺店通开放平台-自助对接-应用管理内应用状态为已上线的应用中查看，调用正式环境注意切换正式环境url=https://api.wangdian.cn/openapi2/


            String proCode = productJSON.getStr("code");
            Map<String, Object>[] goods_list = new Map[1];
            Map<String, Object>[] spec_list = new Map[1];

            JSONObject modelDescription = productJSON.getJSONObject("modelDescription");
            spec_list[0] = new HashMap<String, Object>();
            spec_list[0].put("spec_no", proCode);
            spec_list[0].put("spec_name", modelDescription.getStr("zh_CN")); //规格名称
            String weight = productJSON.getStr("weight");
            if (weight != null) {
                spec_list[0].put("weight", productJSON.getStr("weight"));
            }

            JSONObject name = productJSON.getJSONObject("name");
            goods_list[0] = new HashMap<String, Object>();
            goods_list[0].put("goods_no", proCode);
            goods_list[0].put("goods_type", "1");
            goods_list[0].put("goods_name", name.getStr("zh_CN"));
            goods_list[0].put("class_name", productJSON.getStr("manageClass_Name"));
            JSONObject proDetail =productJSON.getJSONObject("detail");
            JSONObject remark = proDetail.getJSONObject("remark");
            if (remark != null) {
                goods_list[0].put("remark", remark.getStr("zh_CN"));
            }
            String brandName = productJSON.getStr("brand_Name");
            if (brandName != null) {
                goods_list[0].put("brand_name", brandName); // 品牌
            }
            goods_list[0].put("unit_name", productJSON.getStr("unit_Name"));
            goods_list[0].put("spec_list", spec_list);

            //通过第三方json解析工具类fastjson将map解析成json
            String goods_list_json = JSON.toJSONString(goods_list);

            Map<String, Object> params = new HashMap<>();
            params.put("goods_list", goods_list_json);
            try {
                String response = client.execute("goods_push.php", params);
                JSONObject json = JSONUtil.parseObj(response);
                if ("0".equals(json.getStr("code"))) {
                    logger.info("更新物料：" + proCode + "成功");
                }else {
                    logger.error("更新物料：" + proCode + "失败："+json.getStr("message"));
                }
            } catch (Exception e) {
                logger.error("调用接口失败：" + e.getMessage());
            }

       // }
    }

    /**
     * @Author Yjy
     * @Description 物料档案修改事件
     * @Date 16:28 2023/10/11
     **/
    @Async
    @Override
    public void productUpdate(String contentData) {
        // 解析YS数据
        JSONObject contentJSON = JSONUtil.parseObj(contentData);
        JSONObject productJSON = contentJSON.getJSONObject("archive");

        String manageClassCode = productJSON.getStr("manageClass_Code");

       // if (manageClassCode.contains("CP") || manageClassCode.contains("YW") || manageClassCode.contains("FY") || manageClassCode.contains("YG")) {

            // TODO Auto-generated method stub
            WdtClient client = new WdtClient(configProperties.getSid(), configProperties.getKey(), configProperties.getSecret(), configProperties.getUrl());
            //测试环境sid、appkey、密钥请到旺店通开放平台-自助对接-申请测试环境内查看，测试环境url=https://sandbox.wangdian.cn/openapi2/
            //调用正式环境时请将sid、appkey、appsecret切换为实际参数，参数在旺店通开放平台-自助对接-应用管理内应用状态为已上线的应用中查看，调用正式环境注意切换正式环境url=https://api.wangdian.cn/openapi2/

            QueryDto dto = new QueryDto(configProperties.getTenantId(), configProperties.getAppKey(), configProperties.getAppSecret(), configProperties.getGatewayUrl(), configProperties.getTokenUrl());


            String orgCode = productJSON.getStr("orgId_Code");
            String proCode = productJSON.getStr("code");
            Map<String, Object> wlParam = new HashMap<>();
            wlParam.put("productCode",proCode);
            wlParam.put("orgCode",orgCode);
            JSONObject allocationRes = null;
            try {
                 allocationRes = yonsuiteService.ysProductDetailQuery(wlParam,dto);
            }catch (Exception e) {
                logger.error("调用YS物料档案详情查询接口失败：" + e.getMessage());
            }
            JSONObject proData = allocationRes.getJSONObject("data");
            JSONObject proDetails = proData.getJSONObject("detail");

            Map<String, Object>[] goods_list = new Map[1];
            Map<String, Object>[] spec_list = new Map[1];

            JSONObject modelDescription = productJSON.getJSONObject("modelDescription");
            spec_list[0] = new HashMap<String, Object>();
            spec_list[0].put("spec_no", proCode);
            spec_list[0].put("spec_name", modelDescription.getStr("zh_CN")); //规格名称
            String weight = proData.getStr("weight");
            if (weight != null) {
                spec_list[0].put("weight", weight);
            }

            JSONObject name = productJSON.getJSONObject("name");
            goods_list[0] = new HashMap<String, Object>();
            goods_list[0].put("goods_no", proCode);
            goods_list[0].put("goods_type", "1");
            goods_list[0].put("goods_name", name.getStr("zh_CN"));
            goods_list[0].put("class_name", productJSON.getStr("manageClass_Name"));
            String remark = proDetails.getStr("remark1");
            if (remark != null) {
                goods_list[0].put("remark", remark);
            }
            String brandName = proData.getStr("brandName");
            if (brandName != null) {
                goods_list[0].put("brand_name", brandName); // 品牌
            }
            goods_list[0].put("unit_name", productJSON.getStr("unit_Name"));
            goods_list[0].put("spec_list", spec_list);

            //通过第三方json解析工具类fastjson将map解析成json
            String goods_list_json = JSON.toJSONString(goods_list);

            Map<String, Object> params = new HashMap<>();
            params.put("goods_list", goods_list_json);
            try {
                String response = client.execute("goods_push.php", params);
                JSONObject json = JSONUtil.parseObj(response);
                if ("0".equals(json.getStr("code"))) {
                    logger.info("更新物料：" + proCode + "成功");
                }else {
                    logger.error("更新物料：" + proCode + "失败："+json.getStr("message"));
                }
            } catch (Exception e) {
                logger.error("调用接口失败：" + e.getMessage());
            }

        //}
    }

}
